package de.karlNet.sambamanager.view.beans.trees;

import java.util.Iterator;

import javax.faces.event.ActionEvent;

import org.primefaces.event.NodeCollapseEvent;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Controller;

import de.karlNet.sambamanager.ldapController.LdapMemberTree;
import de.karlNet.sambamanager.ldapModel.ITypeCheckerCallback;
import de.karlNet.sambamanager.ldapModel.LdapGroup;
import de.karlNet.sambamanager.ldapModel.LdapObject;
import de.karlNet.sambamanager.ldapModel.LdapUser;
import de.karlNet.sambamanager.view.beans.ManualLeafHandlingTreeNode;

@Controller
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class LdapMemberBean {
	@Autowired
	private LdapMemberTree ldapController;
	private TreeNode root;
	private DefaultTreeNode myRoot;
	private ManualLeafHandlingTreeNode selectedNode;
	@Value("${ldap.baseDN}")
	protected String baseDN;
	@Value("${ldap.dnsName}")
	protected String dnsName;

	public TreeNode getSelectedNode() {
		return selectedNode;
	}

	public TreeNode getRoot() {
		return root;
	}

	public LdapMemberBean() {
		this.root = new ManualLeafHandlingTreeNode("root", new LdapObject(
				this.dnsName, this.baseDN), null);
		this.myRoot = new ManualLeafHandlingTreeNode("root", new LdapObject(
				this.dnsName, this.baseDN), root);
	}

	public void setRoot(ManualLeafHandlingTreeNode root) {
		Iterator<TreeNode> i = this.myRoot.getChildren().iterator();
		while (i.hasNext()) {
			i.next();
			i.remove();
		}
		this.myRoot.setExpanded(false);
		this.myRoot.setData(root.getLdapObject());
	}

	public void onNodeExpand(NodeExpandEvent event) {
		final ManualLeafHandlingTreeNode parent = (ManualLeafHandlingTreeNode) event
				.getTreeNode();
		for (LdapObject ldapObject : this.ldapController.getChildrenOfDN(parent
				.getLdapObject().getDn())) {
			ldapObject.isType(new ITypeCheckerCallback() {
				public void isGroup(LdapGroup ldapGroup) {
					new ManualLeafHandlingTreeNode("group", ldapGroup, parent);
				}

				public void isUser(LdapUser ldapUser) {
					new ManualLeafHandlingTreeNode("user", ldapUser, parent);
				}

			});
		}
	}

	public void setSelectedNode(TreeNode selectedNode) {
		this.selectedNode = (ManualLeafHandlingTreeNode) selectedNode;
	}

	public void displaySelectedSingle(ActionEvent event) {
	}

	public void onNodeCollapse(NodeCollapseEvent event) {
	}

	public void onNodeSelect(NodeSelectEvent event) {
		this.setSelectedNode(event.getTreeNode());
	}

}
